const fs = require( 'fs' );
const path = require( 'path' );
const { NodeSSH } = require( 'node-ssh' );

const project_name = 'backend-manager'

const config = {
  host: '192.168.1.54',
  username: 'root',
  password: 'Gangtise@12345',
  localDir: path.resolve( __dirname, './dist' ),
  remoteDir: `/root/web-page-docker/${project_name}/html`,
  remotePath: `/root/web-page-docker/${project_name}`
};

const ssh = new NodeSSH();

const remoteServiceBuild = () => {
  ssh.execCommand( 'sh build', { cwd: config.remotePath }).then(( result ) => {
    console.log( `The build message is: ${result.stdout}` );

    if ( !result.stderr ) {
      console.log( 'build success!' );

      process.exit( 0 );
    } else {
      console.log( 'Something wrong:', result );
      process.exit( 0 );
    }
  });
};

ssh.connect({
  host: config.host,
  username: config.username,
  password: config.password
}).then(( res ) => {
  console.log( 'SSH login success' );
  ssh.putDirectory( config.localDir, config.remoteDir )
    .then(() => {
      console.log( 'The files is upload successful' );

      remoteServiceBuild()
    }).catch(( err ) => {
      console.log( 'the files upload fail:', err );

      process.exit( 0 );
    });
}).catch(( err ) => {
  console.log( 'SSH conneting fail:', err );
  process.exit( 0 );
});
